<template>
  <!-- 自定义可拖拽表格组件 -->
  <div>
    <el-scrollbar 
      ref="scrollbarRef" 
      always 
      class="table-srollbar" 
      :scrollbar="false" 
      id="scrollbar" 
      @scroll="handleTableScroll" 
      :height="tableHeight"
      :max-height="tableMaxHeight"
      v-loading="loading"
    >
      <table 
        :class="{
          'ruifox-table-new': true,
          'ruifox-content-table-new': true,
          'can-drag': canDrag,
          'doctor-table': modelId == 2
        }"
        :style="{
          'table-layout': border ? '' : 'fixed'
        }"
        ref="ruifoxContentTableRef"
      >
        <colgroup v-if="fieldList?.length">
          <template           
            v-for="(item, index) in fieldList" 
            :key="item.unique || index">
            <col 
              v-show="colShow(item)"
              :width="item.width"
            /> 
          </template>
        </colgroup>
        <thead v-if="fieldList?.length">
          <tr>
            <template v-for="(item, index) in fieldList" :key="item.unique || index">
              <th v-show="colShow(item)"
                :class="{
                  'border': border,
                  'show-text-tip': item?.showTextTip,
                  'col-left-fixed': item?.fixed === 'left',
                  'col-right-fixed': item?.fixed === 'right',
                  'right-first-fixed': item?.rightFirstFixed && !isEndRightVisible,
                  'left-last-fixed': item?.leftLastFixed && isBeforeVisible,
                }"
                :style="item?.sticktStyle">
                <div class="cell"
                  :title="item[tableProps.labelKey]">
                  <div class="default-table-header"
                    :style="{
                      'justify-content': headerTextAlign
                    }"
                  >
                    <!-- title + 固钉 -->
                    <div class="default-table-header-left">
                      <span v-if="!item.hideTitle">{{item[tableProps.labelKey]}}</span>
                      <el-dropdown v-if="item?.showFixedIcon">
                        <div class="el-dropdown-link">
                          <!-- <i class="iconfont iconfont-table icon-option fixed-icon">&#xe611;</i> -->
                          <svg t="1725413034754" class="icon fixed-icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8715" width="14" height="14"><path d="M372.867 442.826l-98.009 98.009 0.433 47.138 195.137 1.72 41.587 387.394 56.059-386.485 193.976 1.678-0.433-48.677-96.681-99.672-46.271-343.136 89.927 0.825-0.364-43.488-389.002-3.454 0.364 43.46 97.379 1.315-44.103 343.374z" fill="#666666" p-id="8716"></path></svg>
                        </div>
                        <template #dropdown>
                          <el-dropdown-menu>
                            <el-dropdown-item v-if="item.fixed !== 'left'" @click="handleFixed(item, 'left')">
                              固定在左侧
                            </el-dropdown-item>
                            <el-dropdown-item v-if="item.fixed !== 'right'" @click="handleFixed(item, 'right')">
                              固定在右侧
                            </el-dropdown-item>
                            <el-dropdown-item v-if="item.fixed" @click="handleFixed(item)">
                              取消固定
                            </el-dropdown-item>
                          </el-dropdown-menu>
                        </template>
                      </el-dropdown>
                    </div>
                    <!-- 右侧插槽 如：条件搜索 -->
                    <div class="default-table-header-right" v-if="item.slotHeader">
                      <slot :name="item.slotHeader" :headerElement="{item,index}">
                        <el-dropdown v-if="item.showStatusIcon?.length">
                          <div class="el-dropdown-link">
                            <i class="iconfont iconfont-table icon-option">&#xe73b;</i>
                          </div>
                          <template #dropdown>
                            <el-dropdown-menu >
                              <el-dropdown-item 
                                v-for="(ele, eleIndex) in item.showStatusIcon" 
                                :key="eleIndex"
                                @click="handleStatusClick(item, ele)"
                              >
                                {{ele.label}}
                              </el-dropdown-item>
                            </el-dropdown-menu>
                          </template>
                        </el-dropdown>
                      </slot>
                    </div>
                  </div>
                </div>
              </th>
            </template>
          </tr>
        </thead>
        <template v-if="tableData.length > 0">
          <!-- 拖拽 -->
          <draggable
            v-if="canDrag"
            :list="tableData"
            animation="180"
            tag="tbody"
            item-key="id"
            drag-class="drag-class"
            :force-fallback="true"
            group="dragArea"
            filter=".unmover"
            class="list-tbody"
            @sort="handleSort"
            @add="handleContentAdd"
            :disabled="dragDisabled"
          >
            <template #item="{ element }">
              <tr>
                <!-- 拖拽 -->
                <template v-for="(_item, _index) in fieldList" :key="_item.unique || _index">
                  <td v-show="colShow(_item)"
                    :class="{
                      'border': border,
                      'show-text-tip': _item?.showTextTip,
                      'col-left-fixed': _item?.fixed === 'left',
                      'col-right-fixed': _item?.fixed === 'right',
                      'right-first-fixed': _item?.rightFirstFixed && !isEndRightVisible,
                      'left-last-fixed': _item?.leftLastFixed && isBeforeVisible,
                    }"
                    :style="_item?.sticktStyle"
                  >
                    <div class="cell" 
                      :title="_item.showTextTip ? showValue(element,_item[tableProps.valueKey]) : null"
                      :style="{
                        'justify-content': textAlign
                      }"
                    >
                      <!-- 具名插槽 -->
                      <slot :name="_item.slot || _item[tableProps.valueKey]" :element="element">
                        <!-- 不适用插槽时，默认显示的内容 -->
                        <span class="unmover" v-html="showValue(element,_item[tableProps.valueKey])"></span>
                      </slot>
                    </div>
                  </td>
                </template>
              </tr>
            </template>
          </draggable>
          <!-- 非拖拽 遍历fieldList为了动态传递插槽-->
          <tbody v-else>
            <DragLbTableColumn
              :columChildData="tableData"
              :fieldList="fieldList"
              v-model:defaultExpandTree="defaultExpandTree"
              :rowKey="rowKey"
              :isBeforeVisible="isBeforeVisible"
              :isEndRightVisible="isEndRightVisible"
              :border="border"
              :textAlign="textAlign"
              @handleExpandChange="handleExpandChange"
              :tableProps="tableProps"
            >
              <template v-for="(_item, _index) in fieldList" :key="_index" v-slot:[_item[tableProps.valueKey]]="{element}" >
                <slot :name="_item[tableProps.valueKey]" :element="element" v-if="_item[tableProps.valueKey] != 'expandChildren'">
                  <span class="unmover" v-html="showValue(element,_item[tableProps.valueKey])"></span>
                </slot>
              </template>
            </DragLbTableColumn>
          </tbody>
        </template>
      </table>
      <!-- 空数据（可自定义插槽） -->
      <div class="ruifox-table-new-no-data" v-if="tableData.length < 1">
        <slot name="noTableData">
          <!-- <i class="iconfont">&#xe642;</i> -->
          <svg t="1728460685872" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="8472" width="70" height="70"><path d="M103.424 621.632h13.632c3.84 0 5.76 3.968 5.76 7.872 0 3.84-3.904 5.888-5.76 5.888h-13.632v13.696c0 3.776-4.032 5.76-5.888 5.76-1.92 0-3.904 0-5.888-1.984-1.92-1.856-1.92-1.856-1.92-3.776v-13.696h-13.696c-3.84 0-5.824-4.032-5.824-5.888 0-3.968 3.904-7.872 5.824-7.872h13.696v-13.696c0-3.904 3.904-5.824 7.808-5.824 3.84 0 5.888 1.92 5.888 5.824v13.696z m903.04-54.528v-13.76c0-1.856 0-4.032-1.856-4.032-2.048-1.856-3.904-1.856-5.952-1.856-3.904 0-5.824 1.856-5.824 5.888v13.76h-13.696c-1.92 0-3.968 0-5.76 1.728-1.984 2.112-1.984 4.032-1.984 5.888 0 4.032 3.84 6.08 5.824 6.08h13.76v13.568c0 3.776 3.84 5.888 5.76 5.888 4.032 0 7.872-3.968 7.872-5.888v-13.568h13.568c3.84 0 5.824-3.968 5.824-6.08 0-3.776-3.84-7.616-5.888-7.616h-11.648z m-497.344 224.192H163.776a13.888 13.888 0 0 1-9.728-3.968 14.592 14.592 0 0 1-3.84-9.728c0-7.808 5.824-13.504 13.568-13.504h62.4a63.296 63.296 0 0 1-7.744-27.392V340.736c0-13.632 5.888-29.248 15.616-38.976a54.144 54.144 0 0 1 38.976-15.616h41.024v-13.632c0-13.696 5.76-29.312 15.616-39.04a54.592 54.592 0 0 1 39.04-15.616h329.6c13.696 0 29.312 5.888 38.976 15.616a54.656 54.656 0 0 1 15.68 39.04v397.888a45.824 45.824 0 0 1-7.936 27.456h76.032c7.808 0 13.76 5.632 13.76 13.568a13.44 13.44 0 0 1-13.76 13.568h-163.84v13.632a44.544 44.544 0 0 1-7.68 27.392h7.68c7.936 0 13.76 5.824 13.76 13.568a13.44 13.44 0 0 1-13.76 13.76H585.088a26.688 26.688 0 0 1-3.84 33.088 25.024 25.024 0 0 1-19.456 7.936 25.024 25.024 0 0 1-19.584-7.936l-33.088-35.136z m50.624-27.2h43.008a26.816 26.816 0 0 0 27.328-27.392V338.816c0-15.616-11.84-27.328-25.536-27.328h-331.52a27.84 27.84 0 0 0-27.2 27.328v397.952c0 15.616 11.584 27.392 27.2 27.392h208.704l-7.808-7.936a29.184 29.184 0 0 1-7.808-27.392l-13.696-13.568a98.688 98.688 0 0 1-130.624-13.568 96.32 96.32 0 0 1 3.84-130.688 96.384 96.384 0 0 1 130.816-3.904c38.912 33.152 44.8 89.536 13.696 130.752l13.568 13.568a28.928 28.928 0 0 1 27.264 7.68l48.768 44.992z m97.536-68.288h41.024a26.688 26.688 0 0 0 27.264-27.328V270.592a26.624 26.624 0 0 0-27.264-27.328H370.56a26.624 26.624 0 0 0-27.2 27.328v15.616h259.456c13.632 0 29.184 5.824 38.848 15.616a54.272 54.272 0 0 1 15.616 38.976v355.008zM175.552 192.512h19.456c5.888 0 9.728 3.904 9.728 9.728s-3.84 9.792-9.728 9.792h-19.456v19.456c0 5.888-3.904 9.792-9.728 9.792-2.048 0-5.888-1.92-7.872-3.904s-1.92-3.904-1.92-7.808v-19.456h-21.44c-1.984 0-5.888 0-7.808-3.904-2.048-1.984-3.968-3.904-3.968-7.808 0-5.888 3.968-9.728 9.728-9.728h21.44v-19.584c0-5.888 3.968-9.728 9.728-9.728 5.888 0 9.728 3.84 9.728 9.728v23.424h2.112zM13.632 777.6c0-7.808 5.824-13.504 13.568-13.504h81.92c7.936 0 13.696 5.696 13.696 13.504 0 7.872-5.76 13.696-13.696 13.696H27.2a14.016 14.016 0 0 1-9.728-3.968 14.784 14.784 0 0 1-3.84-9.728z m433.024-87.68a68.288 68.288 0 0 0 0-97.536 68.288 68.288 0 0 0-97.536 0 68.352 68.352 0 0 0 0 97.536 68.16 68.16 0 0 0 97.536 0zM302.272 368.064c0-7.808 5.888-13.632 13.632-13.632h150.208a13.44 13.44 0 0 1 13.696 13.632 13.376 13.376 0 0 1-13.696 13.696H315.968a15.104 15.104 0 0 1-9.728-3.968c-3.968-3.84-3.968-7.744-3.968-9.728z m0 68.288c0-7.808 5.888-13.632 13.632-13.632H534.4a13.44 13.44 0 0 1 13.824 13.632 13.44 13.44 0 0 1-13.824 13.696H315.968a15.04 15.04 0 0 1-9.728-3.904c-3.968-3.968-3.968-5.824-3.968-9.792z m0 68.288c0-7.872 5.888-13.696 13.632-13.696H411.52a13.44 13.44 0 0 1 13.632 13.696 13.312 13.312 0 0 1-13.632 13.632H315.968a14.72 14.72 0 0 1-9.728-3.968c-3.968-1.856-3.968-5.76-3.968-9.664zM40.896 422.72c-15.616 0-27.264-7.808-35.072-21.44-7.808-13.632-7.808-29.312 0-40.96a40.896 40.896 0 0 1 35.072-21.44c23.488 0 41.024 17.536 41.024 40.96 0 23.296-17.536 42.88-41.024 42.88z m0-21.44a20.416 20.416 0 0 0 17.536-9.728 17.856 17.856 0 0 0 0-19.584c-3.84-7.872-9.728-11.712-17.536-11.712a21.632 21.632 0 0 0-21.376 21.504c1.92 11.648 9.792 19.52 21.376 19.52z m850.496-60.544c-15.552 0-29.44-7.744-35.072-21.44a38.464 38.464 0 0 1 0-40.96c7.68-11.776 21.376-21.44 35.072-21.44 23.36 0 40.96 17.536 40.96 40.96-0.064 23.424-19.456 42.88-40.96 42.88z m0-21.44a20.736 20.736 0 0 0 17.536-9.728c3.968-5.888 3.968-13.696 0-21.44a20.48 20.48 0 0 0-17.536-9.728 21.568 21.568 0 0 0-21.44 21.376c0 9.792 9.728 19.52 21.44 19.52z m0 0" fill="#515151" p-id="8473"></path></svg>
          <span>暂无数据</span>
        </slot>
      </div>
      <el-popover
        v-if="defaultColumConfig && !loading"
        trigger="click"
      >
        <template #reference>
          <span class="choose-title"><i class="iconfont">&#xe66a;</i></span>
        </template>
        <div class="choose-popup" >
          <div class="popup-title">显示列：</div>
          <div class="ruifox-table-new-choose-list" v-if="fieldList?.length">
            <el-checkbox v-for="item in fieldList.filter(item => item.showToUser != false)" :key="item.id" v-model="item.show" :disabled="item.default" :label="item[tableProps.labelKey]"  size="large" @change="handleColCheckChange"/>
          </div>
        </div>
      </el-popover>
    </el-scrollbar>
    <el-affix position="bottom" v-if="tableOverWidth" :offset="affixOffset" ref="affixRefScroll" style="min-height: 11px;">
      <div ref="topScroll" class="top-scroll">
        <div class="top-scroll-content" :style="{ width: topScrollWidth }"></div>
      </div>
    </el-affix>
  </div>
</template>
<script setup>
import { ref, computed, nextTick, watch, onMounted, toRefs } from 'vue'
import draggable from "vuedraggable";
import DragLbTableColumn from './DragLbTableColumn.vue'

/* 
fieldList属性：
  title: 表头名称
  slotHeader: 表头插槽名称
  slot: 表体插槽
  width: 20, //宽度
  name: 对应prop:{data}中数据的键值
  show: 是否显示（不传默认显示，传了则使用show控制）
  showToUser: false, //是否给用户展示勾选
  showOtherPlace: true, //不以单独一列展示（如相关附件展示在内容统计里）
  fixed: 'left', //是否固定列（可选‘left’或‘right’）
  showTextTip: true, //（一行 250px）超出显示省略号 
  minWidth: 200 , //最小宽度（width优先级 > minWidth > showTextTipWidth）
  showFixedIcon: false //是否可操作性冻结列
  showStatusIcon: [{label:'',value:''}] //是否可操作性状态选择
  hideTitle: false, //是否隐藏title
  affixOffset: 65 //固定横向滚动条距底部的高度
  border:  //是否有边框
  tableHeight // 表格高度
  tableMaxHeight // 表格最大高度
  headerTextAlign // 头部th内容位置 flex的justify-content属性
  textAlign //内容td位置 flex的justify-content属性
  row-key="id"  // 唯一标识
  defaultExpandTree // 展开的树形结构项数组，内容为row-key对应的值
  @handleExpandChange="handleExpandChange"  // 展开收起事件
*/
const props = defineProps({
  //数据属性
  fieldList: {
    type: Array,
    default: () => {
      return []
    }
  },
  //数据源
  tableData: {
    type: Array,
    default: () => {
      return []
    }
  },
  //是否拖拽排序
  canDrag: {
    type: Boolean,
    default: false
  },
  //加载状态
  loading: {
    type: Boolean,
    default: false
  },
  //未设置宽度的列的最小宽度
  minWidth: {
    type: Number,
    default: 80
  },
  'default-index': {//序号
    type: Boolean,
    default: false
  },
  'default-checkbox': {//多选
    type: Boolean,
    default: false
  },
  'default-colum-config': {//自定义列选项配置
    type: Boolean,
    default: false
  },
  modelId: {
    type: Number,
    default: null
  },
  affixOffset: { //固定横向滚动条距底部的高度
    type: Number,
    default: 65
  },
  tableHeight: { 
    type: [Number, String],
    default: '100%'
  },
  tableMaxHeight: { 
    type: [Number, String],
    default: '100%'
  },
  border: { 
    type: Boolean,
    default: false
  },
  dragDisabled: { 
    type: Boolean,
    default: false
  },
  headerTextAlign: { 
    type: String,
    default: 'space-between'
  },
  textAlign: { 
    type: String,
    default: 'left'
  },
  rowKey: { 
    type: String,
  },
  defaultExpandTree: { 
    type: Array,
    default: () => {
      return []
    }
  },
  tableProps: {
    type: Object,
    default: () => {
      return {
        valueKey: 'name',
        labelKey: 'title'
      }
    }
  }
})
const { rowKey, border, textAlign, canDrag, headerTextAlign, tableMaxHeight, tableHeight, defaultColumConfig, minWidth } = toRefs(props)
const emits = defineEmits(['update:fieldList','update:defaultExpandTree','tableData','fieldList','handleSort','handleContentAdd','handleSearch','handleExpandChange'])
const tableProps = ref(props.tableProps) 
const showTextTipWidth = ref(250) 
const tableOverWidth = ref(false)  //表格是否有滚动条
const modelId = computed(()=>{return props.modelId})
const fieldList = computed({
  get: () => {
    return props.fieldList
  },
  set: (val) => {
    emits('update:fieldList',val)
  }
})
const tableData = computed({
  get: () => {
    props.tableData.forEach((item, index) => {
      item['default-index'] = index + 1 // 序号
    })
    return props.tableData
  },
  set: (val) => {
    emits('update:tableData',val)
  }
})
const defaultExpandTree = computed({
  get: () => {
    return props.defaultExpandTree
  },
  set: (val) => {
    emits('update:defaultExpandTree',val)
  }
})
// 初始化表头列表（添加序号。多选框等）
const handleDealFieldList = () => {
  try {
    if(fieldList.value.length < 1) return
    fieldList.value.forEach(item => {
      item.minWidthAsWidth = false
      //如果使用了showTextTip属性，则给该列赋默认值250px
      if(!item.width && item.showTextTip){ 
        item.width = item.minWidth || showTextTipWidth.value
        if(item.minWidth) item.minWidth = null
      }
      return item
    })
    if(props.defaultIndex && !fieldList.value.find(item => item[tableProps.value.valueKey] == 'default-index')){
      let obj = {
        [tableProps.value.labelKey]: '序号',
        [tableProps.value.valueKey]:'default-index',
        is_show_control: 1,
        width: 45,
        show: true,
        showToUser: true, //是否给用户展示勾选
        fixed: 'left',
        showFixedIcon: true
      }
      fieldList.value.unshift(obj)
    }
    // 多选
    if(props.defaultCheckbox && !fieldList.value.find(item => item[tableProps.value.valueKey] == 'default-checkbox')){
      let obj = {
        [tableProps.value.labelKey]: '',
        [tableProps.value.valueKey]:'default-checkbox',
        is_show_control: 1,
        width: 45,
        show: true,
        showToUser: false, //是否给用户展示勾选
        textAlign: 'center',
        fixed: 'left',
        showFixedIcon: true
      }
      fieldList.value.unshift(obj)
    }
  } catch (error) {
    if(process.env.NODE_ENV === 'development') console.log('初始化表头列表-错误', error);
  }
}
const colShow = (row) => {
  return (row.show != undefined ? row.show : true) && !row.showOtherPlace
}
// 将所有设置了左固定的列全部移至左部，将所有设置了右固定的列全部移右左部
const handleFiexSort = (arr) => {
  try {
    arr.sort((a, b) => {
      //  a 的 fixed 值为 'left' 且 b 的 fixed 值不为 'left'（可能为空或 'right'）
      if (a.fixed === 'left' && (b.fixed!== 'left' ||!b.fixed)) return -1 
      // 如果 b 的 fixed 值为 'left' 且 a 的 fixed 值不为 'left'（可能为空或 'right'）
      else if (b.fixed === 'left' && (a.fixed!== 'left' ||!a.fixed)) return 1 
      // 同理
      if (b.fixed === 'right' && (a.fixed!== 'right' ||!a.fixed)) return -1
      // 同理
      else if (a.fixed === 'right' && (b.fixed!== 'right' ||!a.fixed)) return 1
      // 其他情况保持原顺序
      else return 0
    })
  } catch (error) {
    if(process.env.NODE_ENV === 'development') console.log('排序', error);
  }
}
// 冻结列初始化
const fixedInit = () => {
  if(fieldList.value.length < 1) return
  try {
    handleFiexSort(fieldList.value) //排序
    //添加类名-冻结时阴影效果
    fieldList.value.forEach(item => {
      item.rightFirstFixed = false
      item.leftLastFixed = false
    })
    let rightFirstFixed = fieldList.value.find(item => item.fixed === 'right')
    if(rightFirstFixed) rightFirstFixed.rightFirstFixed = true
    let leftLastFixed = Array.from([...fieldList.value].reverse()).find(item => item.fixed === 'left' && colShow(item))
    if(leftLastFixed) leftLastFixed.leftLastFixed = true
    // 固定列定位
    fieldList.value.forEach((item, index) => {
      //固定列left赋值
      if(item.fixed === 'left'){ //左固定
        
        // 当前列前面所有固定列的宽度
        let preStickWidth = 0 
        let arr = fieldList.value.slice(0, index).filter(it => it.fixed === 'left' && colShow(it))
        arr.forEach(ele => {
          preStickWidth += ele.width || ele.realWidth
        })
        item.sticktStyle = {
          left: preStickWidth + 'px',
        }
      }else if(item.fixed === 'right'){ //右固定
        // 当前列后面所有固定列的宽度
        let nextStickWidth = 0 
        let arr = fieldList.value.slice(index + 1).filter(it => it.fixed === 'right' && colShow(it))
        arr.forEach(ele => {
          nextStickWidth += ele.width || ele.realWidth
        })
        item.sticktStyle = {
          right: nextStickWidth + 'px',
        }
      }
    })

  } catch (error) {
    if(process.env.NODE_ENV === 'development') console.log('冻结列初始化-错误',error);
  }
}
// 自适应宽度计算处理中（处理设置了最小宽度的列）
const handleCheckOverWidthCol = (scrollBox, usedWidth, defualtWidthColNum, minWidthColNum, cols) => {
  try {
    let average = (Number((scrollBox - usedWidth)/(defualtWidthColNum + minWidthColNum))) 
    // 超出平均宽度的设置了最小宽度的列
    let overWidhtColArr = fieldList.value.filter(item => {
      if(item?.minWidth > average && !item.minWidthAsWidth) return true
    }) 
    if(overWidhtColArr.length){
      overWidhtColArr.forEach(item => {
        item.minWidthAsWidth = true
        item.realWidth = item.minWidth
        usedWidth += item.minWidth
      })
      minWidthColNum = minWidthColNum - overWidhtColArr.length
      handleCheckOverWidthCol(scrollBox, usedWidth, (defualtWidthColNum - minWidthColNum), minWidthColNum, cols)
    }else{
      cols.forEach((col, cIndex) => { 
        let curCol = fieldList.value[cIndex]
        if(colShow(curCol) && !curCol.width && !curCol.minWidthAsWidth){
          curCol.realWidth = curCol.average
          col.setAttribute('width', average)
        }else if(curCol.minWidthAsWidth){
          col.setAttribute('width', curCol.minWidth)
        }
      });
    }
  } catch (error) {
    if(process.env.NODE_ENV === 'development') console.log('自适应宽度计算处理', error);
  }
}
// 自适应宽度计算处理
function calculateColumnWidths() {
  try {
    nextTick(()=>{
      const colgroup = ruifoxContentTableRef.value.querySelector("colgroup")
      if(!colgroup) return
      const cols = colgroup.querySelectorAll("col")
      let scrollBox = scrollbarRef.value.$el.scrollWidth
      let tableMinWidth = 0 //表格最小宽度（固定width + minWidth）
      let defualtWidthColNum = 0 //默认宽度列的数量
      let minWidthColNum = 0 //设置了最小宽度列的数量
      let usedWidth = 0
      cols.forEach((col, cIndex) => { 
        let curCol = fieldList.value[cIndex]
        if(colShow(curCol)){
          // console.log('colr',col.title,col.width);
          // 理论最小宽度为固定宽度width / 最小宽度minWidth / 列最小宽度minWidth 的总和
          tableMinWidth += Number(curCol.width || curCol.minWidth || minWidth.value)
          if(!curCol.width && !curCol.minWidth){ //默认宽度列
            defualtWidthColNum +=1
          }else if(!curCol.width && curCol.minWidth){ //设置了最小宽度的列
            minWidthColNum +=1
            // usedWidth += curCol.minWidth
          }else{ //设置固定宽度的列
            usedWidth += curCol.width
          }
        }
      });
      // 如果父级容器元素宽度比table大，处理剩余宽度
      if(scrollBox > tableMinWidth){
        tableOverWidth.value = false
        ruifoxContentTableRef.value.style.width = scrollBox + 'px'
        // 分两种情况：
        // 1.计算出的平均宽度比某一个最小宽度小，则去除该最小宽度，重新计算，以此类推
        // 2.计算出的平均宽度比所有设置了最小宽度的列都大，直接设置宽度即可
        handleCheckOverWidthCol(scrollBox, usedWidth, defualtWidthColNum, minWidthColNum, cols)
      }else{
        tableOverWidth.value = true
        ruifoxContentTableRef.value.style.width = tableMinWidth + 'px'
        cols.forEach((col, cIndex) => { 
          let curCol = fieldList.value[cIndex]
          if(colShow(curCol) && !curCol.width && !curCol.minWidth){
            col.setAttribute('width', curCol.width || minWidth.value)
          }else if(curCol.minWidth){
            col.setAttribute('width', curCol.minWidth)
          }
        });
      }
    })
  } catch (error) {
    if(process.env.NODE_ENV === 'development') console.log('自适应宽度计算处理-错误', error);
  }
}
// 未使用插槽时展示默认值
const showValue = (item, keyArr) => {//数组key处理
  if (Object.prototype.toString.call(keyArr) === '[object Array]') {
    for (let i = 0; i < keyArr.length; i++) {
      if (!(item[keyArr[i]] === '' || item[keyArr[i]] === undefined || item[keyArr[i]] === null)) {
        return item[keyArr[i]]
      }
    }
  } else if (Object.prototype.toString.call(keyArr) === '[object String]') {
    return item[keyArr]
  }
}
// 排序
const handleSort = (e) => {
  emits('handleSort', e)
}
// 排序
const handleContentAdd = (e) => {
  emits('handleContentAdd', e)
}
// 监听表格横向滚动
const scrollbarRef = ref()
const ruifoxContentTableRef = ref()
const isBeforeVisible = ref(false)
const isEndRightVisible = ref(null)
const handleTableScroll = (scrollLeft) => {
  const w = scrollbarRef.value.$el.scrollWidth
  const c = ruifoxContentTableRef.value?.clientWidth
  if(scrollLeft.scrollLeft){ //是否有滚动条
    isBeforeVisible.value = true
    if(scrollLeft.scrollLeft >= c - w){ //是否滚动到最右边
      isEndRightVisible.value = true
    }else{
      isEndRightVisible.value = false
    }
  }else{
    isBeforeVisible.value = false
  }
  //拖动真实表格 触发模拟滚动条拖动
  if(topScroll.value) topScroll.value.scrollTo(scrollLeft.scrollLeft, 0);
}
// 自定列修改后手动更新滚动条
const handleColCheckChange = () => {
  try {
    nextTick(() => { 
      const w = scrollbarRef.value.$el.scrollWidth
      const c = ruifoxContentTableRef.value?.clientWidth
      if(c > w){ //是否滚动到最右边
        isEndRightVisible.value = false
      }else{
        isEndRightVisible.value = true
      }
      // if(tableData.value.length) calculateColumnWidths()
      if(scrollbarRef.value) {
        scrollbarRef.value.update()
        fixedInit()
      }
    })
  } catch (error) {
    if(process.env.NODE_ENV === 'development') console.log('自定列修改后手动更新滚动条-错误', error);
  }
}

// 手动修改冻结列操作
const handleFixed = (row, fiexdText) => {
  row.fixed = fiexdText
  fixedInit() //冻结列初始化
}

// 列状态条件筛选
const handleStatusClick = (col, val) => {
  let params = {
    key: col[tableProps.value.valueKey],
    value: val.value
  }
  emits('handleSearch', params)
}

// 展开/收起行
const handleExpandChange = (data) => {
  emits('handleExpandChange', data)
}

// 固定横向滚动条
const topScrollWidth = ref(0)
const topScroll = ref()
const affixRefScroll = ref()
const setScrollWidth = () => {
  //设置横向滚顶条宽度值为表格的滚动宽度
  nextTick(() => {
    if(ruifoxContentTableRef.value) topScrollWidth.value = ruifoxContentTableRef.value?.clientWidth + 'px'
    setTimeout(() => {
      if(affixRefScroll.value) affixRefScroll.value.updateRoot()
    }, 0);
  })
}

watch(()=>topScrollWidth.value,()=>{
  nextTick(()=>{
    //拖动模拟滚动条 触发真实表格拖动
    if(topScroll.value){
      topScroll.value.addEventListener('scroll', () => {
        // 表格底部滚动条与顶部同步
        scrollbarRef.value.setScrollLeft(topScroll.value.scrollLeft)
      })
    }
  })
})
watch(fieldList, (newVal, oldVal) => {
  try {
    nextTick(()=>{
      if(oldVal.length < 1 && newVal.length > 0){ //首次加载触发
        handleDealFieldList() //初始化表头列表（添加序号。多选框等）
        fixedInit() //冻结列初始化
      }
      if(newVal.length > 0){
        calculateColumnWidths()
        setScrollWidth()
      }
    })
  } catch (error) {
    if(process.env.NODE_ENV === 'development') console.log('监听fieldList-错误', error);
  }
},{deep:true})
watch(tableData, () => {
  handleDealFieldList() 
  calculateColumnWidths()
  handleColCheckChange()
},{
  deep:true,
  immediate:true
})

onMounted(() => {
  handleColCheckChange() //第一次手动触发表格滚动条
})
</script>
<style lang="scss" scoped>
// 可拖动表格样式
::v-deep(.ruifox-table-new),
.ruifox-table-new {
  border-collapse:collapse;
  background: #fff;
  thead{
    tr{
      width: 100%;
      background: #eff3f8;
      th{
        padding: 10px 0;
        border-bottom: 1px solid #C0C6CC;
        box-sizing: border-box;
        min-width: 0;
        text-overflow: ellipsis;
        vertical-align: middle;
        .cell{
          color: #333333;
          font-size: 12px;
          font-weight: 500;
          box-sizing: border-box;
          line-height: 1.5;
          overflow: hidden;
          overflow-wrap: break-word;
          padding: 0 6px;
          text-overflow: ellipsis;
          white-space: nowrap;
          .default-table-header{
            display: flex;
            justify-content: space-between;
            align-items: center;
            .default-table-header-left,
            .default-table-header-right{
              display: flex;
              justify-content: center;
              align-items: center;
              .icon-option{
                position: relative;
                font-size: 14px;
                margin-left: 5px;
                color: #999;
                cursor: pointer;
                &:hover{
                  color: #666;
                  &::before{
                    display: block;
                  }
                }
                &::before{
                  content: '';
                  position: absolute;
                  top: 50%;
                  left: 50%;
                  transform: translate(-50%,-50%);
                  width: 100%;
                  height: 100%;
                  padding: 5px 3px;
                  z-index: -1;
                  display: flex;
                  background: #e6e6e6;
                  border-radius: 3px;
                  display: none;
                }
              }
              .fixed-icon{
                display: none;
              }
            }
          }
        }
        &:hover{
          .cell {
            color: #000;
          }
          .fixed-icon{
            display: block !important;
          }
        }
      }
      th.border{
        border-right: 1px solid #e3e4e6;
        border-top: 1px solid #e3e4e6;
        &:first-child{
          border-left: 1px solid #e3e4e6;
        }
      }
    }
  }
  tbody{
    tr{
      width: 100%;
      .table-div-check{
        display: flex;
        align-items: center;
        justify-content: center;
        .el-checkbox{
          height: 18px;
        }
      }
      td{
        padding: 10px 0;
        border-bottom: 1px solid #e3e4e6;
        box-sizing: border-box;
        text-overflow: ellipsis;
        vertical-align: middle;
        height: 45px;
        .cell{
          font-size: 12px;
          color: #333;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: normal;
          overflow-wrap: break-word;
          padding: 0 6px;
          line-height: 1.5;
          font-variant: tabular-nums;
          box-sizing: border-box;
          user-select: none;
          display: flex;
          align-items: center;
          span{
            text-overflow: ellipsis;
            white-space: normal;
            overflow-wrap: break-word;
          }
        }
      }
      td.border{
        border-right: 1px solid #e3e4e6;
        &:first-child{
          border-left: 1px solid #e3e4e6;
        }
      }
      td.show-text-tip .cell span{
        white-space: nowrap;
        overflow: hidden;
      }
      .table-td-option{
        .el-dropdown-link{
          color: #4D99F2;
          cursor: pointer;
          .iconfont{
            font-size: 14px;
            margin-top: 2px;
          }
        }
        .el-button.is-link{
          padding: 2px 0;
        }
        .el-button--primary.is-link{
          font-size: 12px;
          &::after{
            display: inline-block;
            position: relative;
            margin: 0 8px;
            height: 12px;
            content: "";
            border-left: 1px solid rgb(203, 203, 203);
          }
        }
        .el-button--primary.is-link:last-child{
          &::after{
            display: none;
          }
        }
        .el-button+.el-button{
          margin-left: 0;
        }
      }
    }
    tr:hover{
      background-color: #e6f0fa;
      .col-left-fixed,
      .col-right-fixed{
        background-color: #e6f0fa;
      }
      .table-td-top .ding-no{
        visibility: visible;
      }
    }
    .drag-class{
      background-color: #F2F6FF;
    }

  }
  /* 冻结 */
  .col-left-fixed,
  .col-right-fixed{
      position: sticky;
      left: 0;
      right: 0;
      /*左上角单元格z-index，切记要设置，不然表格纵向横向滚动时会被该单元格右方或者下方的单元格遮挡*/
      z-index: 1; //列强制最顶层
      background: #fff;
  }
  th.col-left-fixed,
  th.col-right-fixed{
    background: #eff3f8;
  }
  // 冻结时阴影效果
  .col-left-fixed.left-last-fixed{
    &::before{
      content: "";
      position: absolute;
      top: 0px;
      width: 10px;
      right: -10px;
      bottom: -1px;
      overflow-x: hidden;
      overflow-y: hidden;
      box-shadow: none;
      touch-action: none;
      pointer-events: none;
      box-shadow:inset 10px 0 10px -10px rgba(0, 0, 0, .15);
    }
  }
  .col-right-fixed{
    padding-left: 5px;
  }
  .col-right-fixed.right-first-fixed{
    &::before{
      content: "";
      position: absolute;
      top: 0px;
      left: -10px;
      width: 10px;
      bottom: -1px;
      overflow-x: hidden;
      overflow-y: hidden;
      box-shadow: none;
      touch-action: none;
      pointer-events: none;
      box-shadow:inset -10px 0 10px -10px rgba(0, 0, 0, .15);
    }
  }
}
.can-drag{
  tbody{
    tr{
      cursor: move;
    }
  }
}
.choose-title{
  position: absolute;
  top: 9px !important;
  right:20px;
  z-index: 100;
  cursor: pointer;
  i{
    color: #4D99F2;
    font-size: 14px;
  }
}
.ruifox-table-new-choose-list{
  display: flex;
  flex-direction: column;
  max-height: 50vh;
  overflow-y: auto;
  li{
    list-style: none;
  }
}
.ruifox-table-new-no-data{
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 20px 0;
  width: 100%;
  height: fit-content;
  border-bottom: 1px #e3e4e6 solid;
  svg{
    flex-shrink: 0;
    path{
      fill: #AAAAAA;
    }
  }
  &>i{
    font-size: 80px;
    color: #AAAAAA;
  }
  &>span{
    font-size: 12px;
    color: #AAAAAA;
  }
}
::v-deep(.table-srollbar) {
  .el-scrollbar__bar.is-horizontal{
    visibility: hidden;
  }
}
.top-scroll {
  width: 100%;
  overflow-x: auto;
  &::-webkit-scrollbar {
    width: 3px; /* 滚动条的宽度 */
    height: 10px;
    background-color: #f5f5f5 !important; /* 滚动条的背景颜色 */
  }
}
::-webkit-scrollbar-track {
  -webkit-box-shadow:rgba(0,0,0,0.3);
  border-radius:10px;
}
::-webkit-scrollbar {
  width:12px;
}
::-webkit-scrollbar-thumb {
  border-radius:10px;
  background:rgba(0,0,0,0.1);
  -webkit-box-shadow:rgba(0,0,0,0.5);
}
::-webkit-scrollbar-thumb:window-inactive {
  background:rgba(0,0,0,0.1);
}
.top-scroll-content {
  /* 高度不设置的话滚动条出不来 */
  height: 1px; 
}
</style>
